﻿using Google.GData.Client;
using System;
using System.Collections.ObjectModel;

namespace Desktop.Library
{
    /// <summary>
    /// Manage the blogs owned by a particular user.
    /// </summary>
    public class BlogManager : ObservableCollection<AtomEntry>
    {
        #region Constants

        private const string FEED_URL = "http://www.blogger.com/feeds/default/blogs";

        #endregion

        #region Constructors

        public BlogManager(GoogleIdentity user)
        {
            ChangeUser(user);
        }

        public BlogManager()
            : this(null)
        {
        }

        #endregion

        #region Properties

        private GoogleIdentity User { get; set; }
        public Service Service { get; set; }

        #endregion

        #region Methods

        public void Refresh()
        {
            FeedQuery query = new FeedQuery(FEED_URL);
            
            Clear();
            AtomFeed feed = Service.Query(query);
            while ((feed != null) && (feed.Entries.Count > 0))
            {
                foreach (AtomEntry entry in feed.Entries)
                {
                    Add(entry);
                }

                // Do the chunking...
                if (feed.NextChunk != null)
                {
                    query.Uri = new Uri(feed.NextChunk);
                    feed = Service.Query(query);
                }
                else
                {
                    feed = null;
                }
            }
        }

        private void ChangeUser(GoogleIdentity user)
        {
            if (user == null)
            {
                return;
            }
            Service = new Service("blogger", "Desktop");
            Service.Credentials = user.Credentials;
            Refresh();
        }

        public Blog GetBlog(AtomEntry entry)
        {
            string feedUrl = string.Empty;

            // Find the link.rel == feed uri and refresh the tree view:
            foreach (AtomLink link in entry.Links)
            {
                if (link.Rel == BaseNameTable.ServiceFeed)
                {
                    feedUrl = link.HRef.ToString();
                    break;
                }
            }

            if (feedUrl != null)
            {
                return new Blog(Service, entry, feedUrl);
            }
            return null;
        }

        #endregion
    }
}
